<template>
	<div class="quantization_container padding-1 pt-2">
		<div class="quantization_container_top_logo mb-1">
			<img :src="topImg" :class="[$i18n.locale === 'zh_CN'? 'quantization_container_top_logo_home' : 'quantization_container_top_logo_home_en']" alt="">
		</div>
		<div v-if="hasGotFreeMoney == 0" class="quantization_container_game padding-1 mb-1 br-16">
			<img
				class="quantization_container_game_bg1"
				src="@/image/aiQuantization/indexTop/item12.png"
				alt=""
			/>
			<span class="quantization_container_game_text">
				{{ $t("玩太空大逃杀，轻松赚美金！") }}
			</span>
			<div class="quantization_container_game_btn">
				<button @click="getFreeMoney">
					{{ $t("免费领 {money} SAT",{money:freeMoney}) }}
				</button>
				<button @click="inviteFriends">
					{{ $t("立即邀请")}}
				</button>
			</div>
		</div>
		<div class="quantization_container_exclusive padding-1 mb-1 br-16">
			<div class="quantization_container_exclusive_title mb-0">
				<img src="@/image/aiQuantization/indexTop/item6.png" class="mr-0" alt=""/>
				<span>{{ $t("专属权益") }}</span>
			</div>
			<div class="quantization_container_exclusive_only mb-0">
				<span>{{ $t("限购一单") }}</span>
			</div>
			<div class="quantization_container_exclusive_content">
				<div class="quantization_container_exclusive_content_left">
					{{ dataInfo.earning }}
				</div>
				<div class="quantization_container_exclusive_content_right">
					&nbsp;{{ $t("%日收益") }}
				</div>
			</div>
			<div class="quantization_container_exclusive_content mb-0">
				<div class="quantization_container_exclusive_content_left">
				{{ dataInfo.expire }}
				</div>
				<div class="quantization_container_exclusive_content_right">
					&nbsp;{{ $t("日到期") }}
				</div>
			</div>
			<div class="quantization_container_exclusive_content_money mb-0">
				<div>
					{{ $t("投资金额：") }}
				</div>
				<div>
					{{ dataInfo.investment_start + " - " + dataInfo.investment_end + " " + dataInfo.unit }}
				</div>
			</div>
			<div class="quantization_container_exclusive_content">
				<button v-if="has_type" class="quantization_container_exclusive_content_btn" @click="exclusiveBtnClick">{{ $t("立即投资") }}</button>
				<button v-else class="quantization_container_exclusive_content_btn" @click="goMyOrder">{{ $t("我的投资") }}</button>
			</div>
		</div>
		<div class="quantization_container_meal mb-1">
			<div class="quantization_container_meal_top padding-1">
				<div class="quantization_container_meal_top_title mb-2">
					<div class="quantization_container_meal_top_title_left">
						<img src="@/image/aiQuantization/indexTop/item8.png" class="img_one mr-0" alt=""/>
						<span class="mr-0">{{ $t("投资套餐") }}</span>
						<img src="@/image/aiQuantization/indexTop/item15.png" class="img_two" alt=""/>
					</div>
					<div class="quantization_container_meal_top_title_right" @click="goMyOrder">
						<span>{{ $t("我的订单") }}</span>
						<img src="@/image/aiQuantization/indexTop/arrow.png" alt=""/>
					</div>
				</div>
				<div class="quantization_container_meal_top_content mb-0">
					<div class="quantization_container_meal_top_content_left">
						<div class="quantization_container_meal_smallTitle font-left mb-0">
							{{ $t("投入价值") }}
						</div>
						<div class="quantization_container_meal_smallContent font-left">
							{{ dataInfo.mealData.putInto }}
							<span>&nbsp;SUSD</span>
						</div>
					</div>
					<div class="quantization_container_meal_top_content_right">
						<div class="quantization_container_meal_smallTitle font-left mb-0">
							{{ $t("累计收益（SAT）") }}
						</div>
						<div class="quantization_container_meal_smallContent font-left">
							{{ dataInfo.mealData.earnings }}
						</div>
					</div>
				</div>
			</div>
			<div class="quantization_container_meal_bottom padding-1">
				<div class="quantization_container_meal_bottom_earnings mb-1">
					<span>{{ dailyEarning }}%</span>&nbsp;{{ $t("日收益") }}
				</div>
				<div class="quantization_container_meal_bottom_investment mb-0">
					<van-tabs type="card" v-model="earningActive" duration="1" @change="changeEarningActive">
						<van-tab v-for="(item , index) in changeMoneyList" :key="index" :title="item.title.toString()" :name="item.id"></van-tab>
					</van-tabs>
				</div>
				<div class="quantization_container_meal_bottom_input mb-1">
					<input type="number" v-model="investmentAmount" :placeholder="$t('请输入投资金额')"
					@blur="inputInvestmentAmountBlur"
					/>
					<button @click="buyInvestment">{{ $t("立即投资") }}</button>
				</div>
				<div class="quantization_container_meal_bottom_content padding-1 br-8 mb-0">
					<div class="quantization_container_meal_bottom_content_title mb-0 top_title">
						<span>{{ $t("套餐") }}</span>
						<span>{{ $t("日收益率") }}</span>
					</div>
					<div class="quantization_container_meal_bottom_content_title mb-0" v-for="(item,index) in dataInfo.mealDetailData.meals" :key="index">
						<span>{{ item.name }}</span>
						<span>{{ item.meal }}</span>
					</div>
				</div>
				<div class="quantization_container_meal_bottom_hint">
					<div v-html="dataInfo.mealDetailData.mealContent"></div>
				</div>
			</div>
		</div>

		<div class="quantization_container_tendency mb-1">
			<div class="quantization_container_tendency_topImage mb-1">
				<img :src="$i18n.locale === 'zh_CN'? require('@/image/aiQuantization/indexContent/AITitle4_zh.png') : require('@/image/aiQuantization/indexContent/AITitle4_en.png')" alt="">
				<span class="quantization_container_tendency_topImage_title">
					{{ tendencyData.money }}&nbsp;{{ $t("SUSD") }}
				</span>
			</div>
			<div class="quantization_container_tendency_echarts br-16 padding-1">
				<div class="quantization_container_tendency_echarts_content mb-1">
					<ComLineEcharts :data="tendencyEchartsData" :time="tendencyEchartsTime"></ComLineEcharts>
				</div>
				<div class="quantization_container_tendency_echarts_btns">
					<button v-for="(item,index) in tendencyEchartsBtns" :key="index" :class="[index == tendencyEchartsBtnActive? 'btnActive' : '']" @click="echartsBtnChange(index)">{{ item }}</button>
				</div>
			</div>
		</div>

		<div class="quantization_container_quantization mb-1">
			<div class="quantization_container_quantization_topImage mb-1">
				<img :src="$i18n.locale === 'zh_CN'? require('@/image/aiQuantization/indexContent/AITitle5_zh.png') : require('@/image/aiQuantization/indexContent/AITitle5_en.png')" alt="">
			</div>
			<div class="quantization_container_quantization_content br-16 padding-1">
				<ComSemiCircularProgressBar :value="quantizationNum" :strategyType="strategyType"></ComSemiCircularProgressBar>
			</div>
		</div>

		<div class="quantization_container_market">
			<div class="quantization_container_market_topImage mb-1">
				<img :src="$i18n.locale === 'zh_CN'? require('@/image/aiQuantization/indexContent/AITitle6_zh.png') : require('@/image/aiQuantization/indexContent/AITitle6_en.png')" alt="">
			</div>
			<div class="quantization_container_market_list br-16 padding-1">
				<div class="quantization_container_market_list_item mb-1" v-for="(item,index) in marketList" :key="index">
					<div class="market_list_item_left">
						<img :src="item.image" alt="" class="mr-0">
						<span>{{ item.name }}</span>
					</div>
					<div class="market_list_item_right">
						<span>{{ item.money }}</span>
						<span :class="['market_list_item_right_sps' ,'ml-1' , item.rate > 0? 'green' :'red', item.rate > 0? 'greenBkg' :'redBkg']">{{ item.rate }}%</span>
					</div>	
				</div>
			</div>
		</div>
		<ComQuantizationInvestmentPopup :money="investmentAmount" :id="investmentId" :show="showPopup" :popupClose="popupClose" :popCallBack="popCallBack" :orderType="orderType"></ComQuantizationInvestmentPopup>
	</div>
</template>

<script>
import { getAiQuantization , getKLine , buyInvestment, getFreeMoney } from '@/request/aiQuantization'
import { clipboard, confirmDialog } from '@/utils'
import ComLineEcharts from "@/components/comLineEcharts";
import ComSemiCircularProgressBar from "@/components/comSemiCircularProgressBar";
import ComQuantizationInvestmentPopup from "@/components/comQuantizationInvestmentPopup";
import BusinessUtils from '@/utils/business';
import { getLanguage } from '@/lang';
import BinanceService from '@/service/binanceService';

export default {
	name: 'AiQuantization',
	components:{
		ComLineEcharts,
		ComSemiCircularProgressBar,
		ComQuantizationInvestmentPopup
	},
	data(){
		return{
			dataInfo:{ // 专属权益
				earning: '1.30',
				expire: '1095',
				investment_start: '100',
				investment_end: '10000',
				unit: 'SUSD',
				mealData:{ // 投资套餐
					putInto:'1541',
					earnings:'8833.59415'
				},
				mealDetailData:{ // 投资套餐详情
					meals:[
						{
							name:'50-950 SUSD',
							meal:'0.4% - 2%'
						},
						{
							name:'1000-9000 SUSD',
							meal:'0.5% - 2.2%'
						},
						{
							name:'10000-90000 SUSD',
							meal:'0.6% - 2.4%'
						},
						{
							name:'100000-900000 SUSD',
							meal:'0.7% - 2.7%'
						},
					],
					mealContent: ''
				},
			},
			earningActive:50,
			investmentAmount:'',
			tendencyData:{
				money: '0.451'
			},
			strategyType: 2, // 量化策略类型
			tendencyEchartsTime: [["2025-3-1"],],
			tendencyEchartsData:[[0,5,23,35,41,44,66],[0,10,15,35,50,55,66],[0,15,23,25,41,55,66],[0,5,30,35,41,60,66]],
			tendencyEchartsBtns:[this.$t("日K") , this.$t("周K"), this.$t("月K"),  this.$t("年K")],
			tendencyEchartsBtnActive:0,
			quantizationNum:43.5,
			marketList: [],
			showPopup: false,
			has_type: true,
			changeMoneyList: [
				{
					id: 1,
					title: '50'
				},
				{
					id: 1,
					title: '50'
				},
				{
					id: 1,
					title: '50'
				},
				{
					id: 1,
					title: '50'
				},
				{
					id: 1,
					title: '50'
				},
			],
			currencyList:[],
			investmentId: '',
			orderType: 1,
			topImg: require('@/image/aiQuantization/indexTop/AITitle_zh.png'),

			freeMoney: 0, // 免费领取的金额
			inviteCode: '', // 邀请码
			inviteUrl: '', // 邀请链接
			hasGotFreeMoney: 1, // 是否已经领取过免费资金

			showSymbolList: [],
		}
	},
	computed:{
		dailyEarning(){
			let info = this.dataInfo.mealDetailData.meals.find(item => item.id == this.earningActive)
			if(info){
				return info.daily
			}
			return 0
		}
	},
	mounted(){
		let lang = getLanguage();
		if(lang && lang != 'zh_CN'){
			this.topImg = require('@/image/aiQuantization/indexTop/AITitle1_en.png')
		}else{
			this.topImg = require('@/image/aiQuantization/indexTop/AITitle_zh.png')
		}


		this.refreshShowSymbols()
		this.refreshMarketInterval = setInterval(() => {
			this.refreshShowSymbols()
		}, 10000); // 每10秒刷新一次行情数据

		// 请求页面数据
		this.getMarketListData()
	},
	beforeDestroy() {
		if (this.refreshMarketInterval) {
			clearInterval(this.refreshMarketInterval);
		}
	},
	methods:{
		async refreshShowSymbols(){
			if(this.showSymbolList.length == 0) return;
            
			let tickerList = await BinanceService.getSymbolsInfo(this.showSymbolList)
			if(tickerList == null){
				return;
			}

			this.marketList = [];
			for (const symbol of Object.keys(tickerList)) {
				const ticker = tickerList[symbol];
				if (ticker) {
					const baseSymbol = symbol.split('/')[0].toLowerCase();
                    const imageUrl = `https://cdn.jsdelivr.net/gh/atomiclabs/cryptocurrency-icons/svg/color/${baseSymbol}.svg`;

					this.marketList.push({
						image: imageUrl,
						name: symbol,
						money: Number(ticker.last).toFixed(5),
						rate: Number(ticker.percentage).toFixed(2) || 0
					});
				}
			}
		},

		disposeEchartsOptionsData(){
			// 请求来的数据处理成tendencyEchartsData数据
			getKLine({type: this.tendencyEchartsBtnActive+1}).then(res=>{
				if(res.code != 1){
					this.$toast.fail(res.msg)
					return
				}
				let data = res.data.kline.data
				this.tendencyEchartsData = data.flat();
				let date = res.data.kline.time
				this.tendencyEchartsTime =date.flat();
			})
		},
		echartsBtnChange(index){
			// 点击echarts下按钮切换数据
			this.tendencyEchartsBtnActive = index;
			this.disposeEchartsOptionsData()
		},
		getMarketListData(){
			// 请求行情数据
			getAiQuantization({}).then(res=>{
				if(res.code == 1){
					// 行情列表数据
					this.showSymbolList = []
					res.data.hangqing.forEach(item=>{
						let symbolText = item[0]+"/"+item[1]
						this.showSymbolList.push(symbolText)

						// this.marketList.push({
						// 	image: require("@/image/aiQuantization/indexContent/SAT.png"),
						// 	name: item.symbol,
						// 	money: Number(item.currency_price).toFixed(5),
						// 	rate: Number(item.rate).toFixed(2) || 0
						// })
					})
					this.refreshShowSymbols()

					// 专属权益
					this.dataInfo = {
						...this.dataInfo,
						earning: Number(res.data.zhuanshu.max_rate).toFixed(2),
						expire: res.data.zhuanshu.day,
						investment_start: Number(res.data.zhuanshu.min_amount).toFixed(0),
						investment_end: Number(res.data.zhuanshu.max_amount).toFixed(0),
						unit: res.data.zhuanshu.currency,
						id: res.data.zhuanshu.id,
					}

					// 投资套餐收益
					this.dataInfo.mealData = {
						...this.dataInfo.mealData,
						earnings: res.data.my.shouyi,
						putInto: res.data.my.touru,
					}

					this.changeMoneyList = res.data.taocan.map(item=>{
						return {
							id: item.id,
							title: Number(item.min_amount).toFixed(0),
							quota: item.quota,
							max_amount: item.max_amount,
							min_amount: item.min_amount,
						}
					})
					this.investmentAmount = Number(res.data.taocan[0].min_amount).toFixed(0)

					// 价格走势
					this.tendencyData.money = Number(res.data.price).toFixed(4)

					// 投资套餐
					this.dataInfo.mealDetailData.meals = res.data.taocan.map(item=>{
						return {
							id: item.id,
							name: Number(item.min_amount).toFixed(0)+'-'+Number(item.max_amount).toFixed(0)+' '+item.currency,
							meal: Number(item.min_rate).toFixed(1)+'% - '+Number(item.max_rate).toFixed(1)+'%',
							currency: item.currency,
							icon_id: item.icon_id,
							daily: item.taocan_rate
						}
					})

					// 套餐说明
					this.dataInfo.mealDetailData.mealContent = res.data.lianghua_content

					// 量化模型
					this.quantizationNum = res.data.zhendang

					this.strategyType = res.data.zhendang_type

					// 是否有专属投资
					this.has_type = !res.data.has_zhuanshu

					this.freeMoney = res.data.new_welfare_benefits
					this.inviteCode = res.data.user_code
					this.inviteUrl = res.data.invite_url
					this.hasGotFreeMoney = res.data.is_get_welfare_benefits
				}
			})
			this.disposeEchartsOptionsData()
		},
		exclusiveBtnClick(){
			this.investmentId = this.dataInfo.id
			this.showPopup = true;
		},
		popupClose(){
			this.orderType = 1
			this.showPopup = false;
		},
		async popCallBack(data){
			const result = await confirmDialog({
				title: this.$t('请输入支付密码'),
				confirmText: this.$t('确认'),
				cancelText: this.$t('取消'),
			})
			
			if (result) {
				// 用户点击了确认
				let obj = {
					id: data.id,
					money: data.money,
					currency: data.currency,
					coupon: data.coupon,
					paypassword: result
				}
				buyInvestment(obj).then(res=>{
					if(res.code == 1){
						this.getMarketListData()
						this.$toast.success(res.msg)
						this.showPopup = false;
						// 在这做专属投资确认接口
					}else{
						this.$toast.fail(res.msg)
					}
				})
			} else {
				// 用户点击了取消
				console.log(false)
			}
		},
		goMyOrder(){
			if (this.$route.name !== 'MyOrder') {
				this.$router.push({
					name: 'MyOrder'
				})
			}
		},
		changeEarningActive(name , title){
			this.investmentAmount = title
		},

		inputInvestmentAmountBlur(){
			if(this.investmentAmount == ''){
				this.investmentAmount = '0'
			}
		},
		checkInvestmentAmount(){
			let info = this.changeMoneyList.find(item => item.id == this.earningActive)
			if(!info){
				return false
			}else{
				if(Number(this.investmentAmount) < Number(info.min_amount)){
					this.$toast.fail(this.$t('最小投资额度') + " " + Number(info.min_amount).toFixed(0))
					this.investmentAmount = info.min_amount
					return false
				}

				if(Number(this.investmentAmount) > Number(info.max_amount)){
					this.$toast.fail(this.$t('最大投资额度') + " " + Number(info.max_amount).toFixed(0))
					this.investmentAmount = info.max_amount
					return false
				}

				if(Number(this.investmentAmount) > info.quota){
					this.$toast.fail(this.$t('剩余额度') + " " + Number(info.quota).toFixed(0))
					this.investmentAmount = String(info.quota)
					return false
				}
			}
			return true
		},

		async buyInvestment(){
			if(this.checkInvestmentAmount() === false){
				return
			}

			this.investmentId = this.earningActive
			this.orderType = 2
			console.log(this.investmentId , this.orderType)
			this.showPopup = true;
			// 购买套餐
			// const result = await confirmDialog({
			// 	title: this.$t('请输入支付密码'),
			// 	confirmText: this.$t('确认'),
			// 	cancelText: this.$t('取消'),
			// })
			// if(result){
			// 	let num = this.dataInfo.mealDetailData.meals.filter(item => item.id == this.earningActive)
			// 	let obj = {
			// 		id: this.earningActive,
			// 		money: this.investmentAmount,
			// 		currency: num[0].icon_id,
			// 		coupon: '',
			// 		paypassword: result
			// 	}
			// 	buyInvestment(obj).then(res=>{
			// 		if(res.code == 1){
			// 			this.getMarketListData()
			// 			this.$toast.success(res.msg)
			// 		}else{
			// 			this.$toast.fail(res.msg)
			// 		}
			// 	})
			// }else{

			// }
		},

		getFreeMoney(){
			getFreeMoney({}).then(res=>{
				if(res.code == 1){
					this.$toast.success(this.$t('领取成功'))
					this.hasGotFreeMoney = 1
				}else{
					this.$toast.fail(res.msg)
				}
			})
		},

		async inviteFriends(){
			try {
				await clipboard.copy(BusinessUtils.getInvitePath(this.inviteUrl, this.inviteCode));
				this.$toast.success(this.$t('复制成功'));
			} catch {
				this.$toast.fail(this.$t('复制失败'));
			}
			
		},
	}
}
</script>

<style>

</style>